package com.pxmeta.app.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.pxmeta.app.entity.AppVersion;
import com.pxmeta.app.entity.Menu;
import com.pxmeta.app.entity.vo.CheckVersionVO;
import com.pxmeta.app.entity.vo.HomeVO;
import com.pxmeta.app.entity.vo.MenuVO;
import com.pxmeta.app.service.IAppVersionService;
import com.pxmeta.app.service.IMenuService;
import com.pxmeta.circle.entity.Circle;
import com.pxmeta.circle.entity.UserCircle;
import com.pxmeta.circle.service.ICircleService;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.constant.TextConstance;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.utils.CodeUtil;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.dynamic.entity.dto.DynamicDTO;
import com.pxmeta.dynamic.service.IDynamicService;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.dto.UserPositionDTO;
import com.pxmeta.user.entity.vo.RecommendUserVO;
import com.pxmeta.user.service.IUserService;
import com.pxmeta.user.service.NearbyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "首页", value = "首页")
@CrossOrigin
public class IndexController {

    private final ICircleService circleService;
    private final IAppVersionService versionService;
    private final NearbyUserService nearbyUserService;
    private final IUserService userService;
    private final IMenuService menuService;
    private final IDynamicService dynamicService;


    @SaCheckLogin
    @ApiOperation(value = "获取我的圈子列表")
    @GetMapping("/getUserCircle")
    @ApiImplicitParam(paramType = "header",name = "Authorization")
    public AjaxResult<List<Circle>> getUserCircle(){
        Long userId = SecurityUtils.getUserId();
        List<Circle> list = circleService.getCircleList(userId, 0, 1, 10, null);
//        List<Circle> list = circleService.getUserCircle(userId);
        return AjaxResult.success(list);
    }


    @SaCheckLogin
    @ApiOperation("获取轮播图列表")
    @GetMapping("/getBannerList")
    public AjaxResult getBannerList(){

        return AjaxResult.success();
    }

    @GetMapping("/getShareUrl")
    @SaCheckLogin
    @ApiOperation("获取分享链接")
    public AjaxResult getShareUrl(){
        Long userId = SecurityUtils.getUserId();
        String url = "https://h5.pengxinmeta.com/down?userId="+userId;
        Map<String, Object> map = Maps.newHashMap();
        map.put("url", url);
        return AjaxResult.success(map);
    }

    @SaCheckLogin
    @ApiOperation(value = "保存当前用户位置信息")
    @PostMapping("/savePosition")
    public AjaxResult saveUserPosition(@RequestBody UserPositionDTO dto){
        Long userId = SecurityUtils.getUserId();
        String add = nearbyUserService.save(userId.toString(), dto.getLongitude(), dto.getLatitude());
        userService.saveAddress(userId, add);

        return AjaxResult.success();
    }
    @SaCheckLogin
    @ApiOperation(value = "获取首页菜单")
    @GetMapping("/getMenuList")
    public AjaxResult<HomeVO> getMenuList(){

        LambdaQueryWrapper<Menu> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(Menu::getSort);
        List<Menu> list = menuService.list();
        List<MenuVO> menuList = list.stream().map(l -> {
            MenuVO vo = new MenuVO();
            vo.setType(l.getType());
            vo.setName(l.getName());
            vo.setOrder(l.getSort());
            vo.setIsHiddenPlay(l.getIsHiddenPlay());
            return vo;
        }).collect(Collectors.toList());

        HomeVO homeVO = new HomeVO();
        homeVO.setMenuList(menuList);
        homeVO.setIsHiddenCard(false);

        Long userId = SecurityUtils.getUserId();
        homeVO.setIsHiddenPlay(menuList.get(0).getIsHiddenPlay());
//        if (associationId==null){
//            homeVO.setIsHiddenPlay(true);
//        }else {
//            homeVO.setIsHiddenPlay(false);
//        }

        return AjaxResult.success(homeVO);
    }

    private MenuVO createMenu(String name, Integer order, Integer type){
        MenuVO menuVO = new MenuVO();
        menuVO.setName(name);
        menuVO.setOrder(order);
        menuVO.setType(type);
        return menuVO;
    }


    @SaCheckLogin
    @ApiOperation(value = "获取推荐用户列表")
    @GetMapping("/getRecommendUsers")
    public AjaxResult<List<RecommendUserVO>> getRecommendUsers(@RequestParam(required = false) Double userLng,
                                                               @RequestParam(required = false) Double userLat){
        Long userId = SecurityUtils.getUserId();
        List<RecommendUserVO> userList = userService.getRecommendUsers(userId, userLng, userLat);
        return AjaxResult.success(userList);
    }

    @GetMapping("/getRecommendDynamicList")
    @ApiOperation("获取推荐动态列表")
    @SaCheckLogin
    public AjaxResult getRecommendDynamicList(@RequestParam Integer page,
                                              @RequestParam Integer size,
                                              @RequestParam Integer type){
        Long userId = SecurityUtils.getUserId();
        List<DynamicDTO> records = dynamicService.getList(page, size, Status.SUCCESS.getValue()).getRecords();
        return AjaxResult.success(records);
    }


    @ApiOperation(value = "获取圈子详情",response = Circle.class)
    @GetMapping("/getCircleDetail")
    public AjaxResult<Circle> getCircleDetail(@RequestParam Long circleId){
        Long userId = SecurityUtils.getUserId();
        Circle circle = circleService.getDetail(circleId);
        List<Long> userCircleIds = circleService.getUserCircle(userId).stream().map(Circle::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(userCircleIds)){
            boolean isJoin = userCircleIds.contains(circleId);
            circle.setIsJoin(isJoin);
        }
        return AjaxResult.success(circle);
    }


    @ApiOperation(value = "获取用户协议")
    @GetMapping("/getPrivacyPolicy")
    public AjaxResult<Map> getPrivacyPolicy(){
        Map<String, Object> map = Maps.newHashMap();
        map.put("content", TextConstance.CONTENT);
        return AjaxResult.success(map);
    }


    @ApiOperation(value = "检查版本是否需要更新")
    @GetMapping("/checkVersion")
    public AjaxResult<CheckVersionVO> checkVersion(@RequestParam String currentVersion,
                                   @RequestParam String platform){

        AppVersion appVersion = versionService.getNewestVersion(platform);
        CheckVersionVO vo = new CheckVersionVO();
        if (appVersion == null){
            vo.setUpdate(false);
            return AjaxResult.success(vo);
        }

        String newestVersion = appVersion.getVersion();
        Boolean update = checkUpdate(newestVersion, currentVersion);
        if (update){
            vo.setExplain(appVersion.getVersionExplain());
            vo.setUpdate(true);
            if (platform.equals("android")){
                vo.setUrl("https://pengxinapp.oss-cn-beijing.aliyuncs.com/app/app-release.apk");
            }else {
                vo.setUrl("https://apps.apple.com/cn/app/%E7%A2%B0%E5%BF%83-%E6%89%BE%E5%88%B0%E5%B1%9E%E4%BA%8E%E4%BD%A0%E7%9A%84%E5%9C%88%E5%AD%90/id6443760367");
            }
        }else {
            vo.setUpdate(false);
        }
        vo.setIsVerifySuccess(Boolean.TRUE);
        return AjaxResult.success(vo);
    }

   private static Boolean checkUpdate(String newestVersion, String currentVersion){
       String[] split = newestVersion.split("\\.");
       String str1 = split[0];
       String str2 = split[1];
       String str3 = split[2];
       int updateNum1 = Integer.parseInt(str1);
       int updateNum2 = Integer.parseInt(str2);
       int updateNum3 = Integer.parseInt(str3);

       String[] split1 = currentVersion.split("\\.");
       String str11 = split1[0];
       String str12 = split1[1];
       String str13 = split1[2];
       int currentNum1 = Integer.parseInt(str11);
       int currentNum2 = Integer.parseInt(str12);
       int currentNum3 = Integer.parseInt(str13);




       if (currentNum1 < updateNum1){
           return Boolean.TRUE;
       }

       if (currentNum1 == updateNum1 && currentNum2 < updateNum2){
           return Boolean.TRUE;
       }

       if (currentNum1 == updateNum1 && currentNum2 == updateNum2 && currentNum3 < updateNum3){
           return Boolean.TRUE;
       }

       return Boolean.FALSE;
   }


}
